package com.pat.web.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;
import com.pat.common.util.OssUtil;
import com.pat.web.ApiResponse;
import com.pat.web.model.UploadObj;

public class UploadController extends Controller{

	
	public void uploadPic() throws FileNotFoundException{
		try {
			InputStream is = getRequest().getInputStream();
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			byte[]data = new byte[4096];
			int i;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while((i = is.read(data))!=-1){
				baos.write(data, 0, i);
			}
			byte[]orignal = Base64.getDecoder().decode(baos.toByteArray());
			baos.close();
			
			
			String absolutePath = OssUtil.uploadPIC(name, new ByteArrayInputStream(orignal));
			UploadObj upload = new UploadObj();
			upload.setId(name);
			upload.setName(name);
			upload.setPrefix("http://"+OssUtil.BUCKET+"."+OssUtil.OSS_PREFIX+"/"+OssUtil.PRFIX);
			upload.setFileType(OssUtil.PIC_DEFAULT_TYPE);
			upload.setAbsolutePath(absolutePath);
			upload.save();
			
			ApiResponse api = new ApiResponse();
			api.setStatusCode("0000");
			api.setData(upload);
			render(new JsonRender(JSON.toJSONString(upload)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
